import React from 'react';
import ReactDOM from 'react-dom';
import 'publicPath';
import './checkIsImpError';

import { removeCookie } from '@packages/lib-cookie';
import { execWxJob } from '@packages/lib-exec';
import { pageBack } from '@packages/lib-history';
import os from '@packages/lib-os';

import { LazyImage } from 'components/LazyImage';

// 加载 WPT 适配器
import * as wptAdapter from '../wpt.adapter';

import Link from './components/Link';
import appBridge from './wptBridge/oldVersion/appBridge';
import apiConfig from './apiConfig';
import { getRootProps, pushState, replaceUrl, segment } from './base';
import { event, initLazy, Interval, onTouchEnd, pageChange, scroll, shareEvent } from './global';
import { computedPosition, fullScreenFit, getTopNavHeight } from './heightChangeFit';
import Model from './model';
import { report, reportError } from './report';
import Util from './util';
import wptApp from './wptApp';
import { initWptBridge, wptBridge, wptBridgeListener } from './wptBridge';
import { mockUserAction } from './wx';
import { xcxNavigateBack, xcxNavigateTo } from './xcxApi';

import 'wptd/dist/wptd.css';
import './css/style.less';
import './css/wptFontMain.less';

if (
    os.wechatPhone ||
    os.wpt || // ios微信客户端开启
    (os.PCPlantform && os.phone) // pc模拟器也开启手势返回
) {
    // eslint-disable-next-line no-unused-expressions
    import('./slideMove');
}

if (process.env.USER) {
    // 开发环境引入代理用户名，以便扫码代理
    window.__proxyHost__ = process.env.USER;
}

// 非生产环境增加矫正时间逻辑
if (WPT.isGray || 't.weipaitang.com' === window.location.hostname) {
    // 取当前时间
    let nowTime = WPT.nowTime;
    // 劫持
    Object.defineProperty(WPT, 'nowTime', {
        set(newValue) {
            nowTime = newValue;
            const start = Date.now();
            WPT.getNowTime = () => {
                const timeSpace = Math.round((Date.now() - start) / 1000);
                return nowTime + timeSpace;
            };
        },
        get() {
            return nowTime;
        },
    });
}

// 公共组件
window.Link = Link;
window.LazyImage = LazyImage;
window.React = React;
window.ReactDOM = ReactDOM;
window.Navigator = () => null;
initWptBridge();

/**
 * https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
 * 当页面刷新/redirect时，浏览器不记录滚动条高度
 * 如果设置了manual，safari手势回退会导致页面闪动
 */
if (
    (os.wechat || os.android || os.PCPlantform) && // pc和微信可用
    !(os.ios && os.xcx) && // ios微信小程序支持手势返回，不做处理
    'scrollRestoration' in window.history
) {
    try {
        window.history.scrollRestoration = 'manual';
    } catch (err) {
        console.log('部分浏览器scrollRestoration属性为readonly', err);
    }
}
// 直接更改window.WPT 避免造成对象引用不一致
Object.assign(window.WPT, wptAdapter, {
    // 全局性功能
    shareEvent,
    Interval,
    scroll,
    initLazy,
    onTouchEnd,
    event,
    os,
    pageChange,
    appBridge,
    noHeadImage: 'https://cdn.weipaitang.com/res/img/nohead.jpg',
    segment,
    pushState,
    replaceUrl,
    // 常用工具函数
    getRootProps,
    // 工具库
    Util,
    // 模态框, 加载提示等
    Model,
    // 页面组件装饰器
    from: {},
    apiConfig,
    Navigator,
    wptApp,
    report,
    reportError,
    LazyImage,
    // 小程序api
    xcxNavigateTo,
    xcxNavigateBack,
    mockUserAction,
    // app 原生交互
    wptBridge,
    wptBridgeListener,
    // 适配全屏webview
    fullScreenFit,
    computedPosition,
    getTopNavHeight,
    pageBack,
});

require('./plugins');

// 微信环境需要执行的操作
execWxJob(() => {
    os.device = 'wechat';
    localStorage.setItem('WPT.wechat', 1);
    setTimeout(() => {
        if (os.device != 'wechat') {
            localStorage.removeItem('WPT.wechat');
        }
    }, 3000);

    const { pathname, href } = window.location;
    // 有证链证书，不自动授权

    // if (!WPT.userinfo.userinfoUri) {
    //     WPT.load.loadingWaver(
    //         '自动授权...',
    //         () => {
    //             const url = Util.urlAddQuery(href, { microMessenger: 1 });
    //             WPT.redirect(url);
    //         },
    //         1000
    //     );
    // }
});

// 如果ssuri不存在的话，删除cookie，微信浏览器的session，在浏览器关闭时，并不会被删除
if (!WPT.sessionStorage.getItem('ssuri') && os.wechat) {
    removeCookie('ssuri');
}
// 判断微拍堂app
// TODO:
if (window.$ && $.os) {
    $.os.wpt = !!navigator.userAgent.toLowerCase().match('wptmessenger');
}

WPT.curStartUrl = window.location.href;
let url = window.location.pathname + window.location.search;
let isBack = false;
if (window.location.search.indexOf('redirect=true') != -1) {
    let search = window.location.search;
    if (search.indexOf('?redirect=true') != -1) {
        if (search.indexOf('?redirect=true&') != -1) {
            search = search.replace('?redirect=true&', '?');
        } else {
            search = search.replace('?redirect=true', '');
        }
    } else if (search.indexOf('&redirect=true') != -1) {
        search = search.replace('&redirect=true', '');
    }
    url = window.location.pathname + search;
    isBack = true;
    WPT.goOutside = true;
}

// if (['native', 'web-phone'].includes(os.device)) {
//     // app 端和网页移动端 默认关注
//     WPT.userinfo.isSubscribe = 1;
// }

// 监听页面是否滑动
(() => {
    let startX = 0;
    let endX = 0;
    let touchendTime = 0;
    WPT.move = {};
    if (!os.ios) {
        return;
    }
    window.addEventListener('touchstart', (e) => {
        startX = e.changedTouches[0].clientX;
        endX = 0;
        WPT.move = {
            isMove: false,
            isBack: false,
            isForward: false,
        };
    });
    window.addEventListener(
        'touchmove',
        (e) => {
            endX = e.changedTouches[0].clientX;
            if (endX != 0 && Math.abs(Math.abs(startX) - Math.abs(endX)) > 10) {
                window.clearTimeout(touchendTime);
                WPT.move.isMove = true;
                if (Math.abs(startX) > Math.abs(endX)) {
                    WPT.move.isBack = false;
                    WPT.move.isForward = true;
                } else {
                    WPT.move.isBack = true;
                    WPT.move.isForward = false;
                }
            }
        },
        this,
        false
    );
    window.addEventListener('touchend', () => {
        touchendTime = setTimeout(() => {
            WPT.move = {
                isMove: false,
                isBack: false,
                isForward: false,
            };
        }, 400);
    });
    // ios下系统键盘隐藏后，界面视觉上回到原位置，实际位置可能还停留在键盘收起之前，之后再点击界面出现无响应情况
    window.addEventListener(
        'blur',
        () => {
            $(window).scrollTop($(window).scrollTop());
        },
        {
            capture: true,
        }
    );
})();

WPT.loginTime = Date.now() / 1000; // window.localStorage.getItem('login-time') || Date.now() / 1000 - 7300;
WPT.showPage(url, true, isBack, true); // isBack == true 不清除sessionStorage里信息

// 如果有 wptForceLogin 则需要强行唤出登录框进行登录 && 是百度xcx
if (Util.query().wptForceLogin && Util.query().wptForceLogin !== 'addPrice' && !WPT.userinfo.userinfoUri && os.bdXcx) {
    WPT.login();
}


export * from '../wpt.adapter';

export {
    // 全局性功能
    shareEvent,
    Interval,
    scroll,
    initLazy,
    onTouchEnd,
    event,
    os,
    appBridge,
    // 页面切换相关
    segment,
    pushState,
    replaceUrl,
    // 常用工具函数
    // 工具库
    Util,
    // 模态框, 加载提示等
    Model,
    // 页面组件装饰器
    apiConfig,
    wptApp,
    report,
    reportError,
    LazyImage,
    // 小程序api
    xcxNavigateTo,
    xcxNavigateBack,
    mockUserAction,
    // app 原生交互
    wptBridge,
    wptBridgeListener,
    // 适配全屏webview
    fullScreenFit,
    computedPosition,
    getTopNavHeight,
    pageBack,
};

export default {
    ...wptAdapter,
    // 全局性功能
    shareEvent,
    Interval,
    scroll,
    initLazy,
    onTouchEnd,
    event,
    os,
    appBridge,
    // 页面切换相关
    segment,
    pushState,
    replaceUrl,

    // 工具库
    Util,
    // 模态框, 加载提示等
    Model,
    // 页面组件装饰器

    from: {},
    apiConfig,
    Navigator,
    wptApp,
    report,
    reportError,
    LazyImage,
    // 小程序api
    xcxNavigateTo,
    xcxNavigateBack,
    mockUserAction,
    // app 原生交互
    wptBridge,
    wptBridgeListener,
    // 适配全屏webview
    fullScreenFit,
    computedPosition,
    getTopNavHeight,
    pageBack,
};

require('./testTva');
